<template>
  <el-dialog
    :close-on-click-modal="false"
    title="机械设备租赁合同明细"
    :visible.sync="show"
    width="1000px"
    center
  >
    <el-form ref="form" :rules="rules" style="padding-top: 10px;" :model="form" label-width="120px">
      <div class="com-form-title">基础信息</div>
      <el-row>
        <el-col :span="8">
          <el-form-item label="租赁编号" prop="leaseNumber">
            <el-input v-model="form.leaseNumber" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="合同编号" prop="contractNumber">
            <el-input v-model="form.contractNumber" :disabled="true" placeholder="自动生成" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="合同名称" prop="contractName">
            <el-input v-model="form.contractName" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="合同金额" prop="contractAmount">
            <el-input v-model="form.contractAmount" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="甲方名称" prop="employerName">
            <el-input v-model="form.employerName" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="甲方签订人" prop="employerSign">
            <el-input v-model="form.employerSign" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="签订时间" prop="signTime">
            <el-date-picker v-model="form.signTime" style="width:100%" type="date" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目名称" prop="address">
            <el-input v-model="form.projectName" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="乙方名称" prop="employeeName">
            <!-- <el-input v-model="form.employeeName" :disabled="disableForm" /> -->
            <el-input v-model="form.employeeName" :disabled="disableForm || optType !== 'add'">
              <i slot="suffix" class="el-input__icon el-icon-circle-plus-outline" @click="optType === 'add' ? showBidOpenInfoModal = true : null" />
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="乙方签订人" prop="employeeSign">
            <el-input v-model="form.employeeSign" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="租赁类型" prop="leaseType">
            <el-select v-model="form.leaseType" :disabled="disableForm" style="width: 100%;" placeholder="请选择租赁类型">
              <el-option v-for="item in deviceLeaseContractInfoLeaseType" :key="item.name" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="租赁性质" prop="leaseNature">
            <el-select v-model="form.leaseNature" :disabled="disableForm" style="width: 100%;" placeholder="请选择租赁性质">
              <el-option v-for="item in deviceLeaseContractInfoLeaseNature" :key="item.name" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="会签类型" prop="countersignType">
            <el-select v-model="form.countersignType" :disabled="disableForm" style="width: 100%;" placeholder="请选择会签类型">
              <el-option v-for="item in deviceLeaseContractInfoCountersignType" :key="item.name" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="付款方式" prop="payType">
            <el-input v-model="form.payType" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="质保金额" prop="warrantyAmount">
            <el-input v-model="form.warrantyAmount" :disabled="disableForm" />
          </el-form-item>
        </el-col> -->
        <!-- <el-col :span="8">
          <el-form-item label="质保金开始日期" prop="warrantyStartTime">
            <el-date-picker v-model="form.warrantyStartTime" style="width:100%" type="date" :disabled="disableForm" />
          </el-form-item>
        </el-col> -->
        <!-- <el-col :span="8">
          <el-form-item label="质保金截止日期" prop="warrantyEndTime">
            <el-date-picker v-model="form.warrantyEndTime" style="width:100%" type="date" :disabled="disableForm" />
          </el-form-item>
        </el-col> -->
      </el-row>

      <div style="padding-bottom: 10px;">
        <el-button type="primary" @click="showTargetSetListModal = true">引入设备</el-button>
        <el-button type="primary" @click="addRow">新增行</el-button>
        <el-button type="primary" @click="deleteRow">删除行</el-button>
      </div>
      <com-table
        v-model="selectRow"
        highlight-current-row
        :data="targetList"
        :columns="columns"
        :no-page="true"
      >
        <template v-slot:devDirCode="{row}">
          <el-input v-model="row.devDirCode" />
        </template>
        <template v-slot:devDirName="{row}">
          <el-input v-model="row.devDirName" />
        </template>
        <template v-slot:specification="{row}">
          <el-input v-model="row.specification" />
        </template>
        <template v-slot:unit="{row}">
          <el-input v-model="row.unit" />
        </template>
        <template v-slot:count="{row}">
          <el-input v-model="row.count" @input="inputCount" />
        </template>
        <template v-slot:startTime="{row}">
          <el-date-picker v-model="row.startTime" style="width:100%" type="date" :disabled="disableForm" />
        </template>
        <template v-slot:endTime="{row}">
          <el-date-picker v-model="row.endTime" style="width:100%" type="date" :disabled="disableForm" />
        </template>
        <template v-slot:unitPrice="{row}">
          <el-input v-model="row.unitPrice" @input="inputUnitPrice" />
        </template>
        <template v-slot:taxRate="{row}">
          <el-input v-model="row.taxRate" />
        </template>
        <template v-slot:taxes="{row}">
          <el-input v-model="row.taxes" />
        </template>
        <template v-slot:sumPrice="{row}">
          <el-input v-model="row.sumPrice" disabled />
        </template>
        <template v-slot:planLease="{row}">
          <el-input v-model="row.planLease" />
        </template>
        <template v-slot:remark="{row}">
          <el-input v-model="row.remark" />
        </template>
        <template v-slot:options="{row}">
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteTarget(row)">删除</el-button>
        </template>
      </com-table>
      <el-button style="margin-top:10px;" type="primary" @click="showFileModal = true">附件资料({{ fileList.length }})</el-button>
      <file-uploader v-model="fileList" :show-modal.sync="showFileModal" :disabled="disableForm" :can-download="optType==='detail'" />

    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="show = false">取 消</el-button>
      <el-button type="primary" @click="saveDoc">确 定</el-button>
    </span>
    <!-- <supplier-list :show-modal.sync="showTargetSupplierSetListModal" @getSelectedRows="getSelectedRowsSupplier" /> -->
    <bid-open-info :show-modal.sync="showBidOpenInfoModal" @getSelectedRows="getSelectedRowsBidOpenInfo" />

    <tree-modal title="机械设备选择(多选)" :show-modal.sync="showTargetSetListModal" :columns="columns" :api-obj="{tree:getMachineDirectoryTree,list:getMachineDeviceDetailList}" @getSelectedRows="getSelectedRows" />

  </el-dialog>
</template>

<script>
import { addDeviceLeaseContractInfo, updateDeviceLeaseContractInfo, getDeviceLeaseContractInfoDetail } from '@/api/contractManage'
import { getAreaList } from '@/api/common'
import { deviceLeaseContractInfoLeaseType, deviceLeaseContractInfoLeaseNature, deviceLeaseContractInfoCountersignType, workflowStatus } from '@/utils/dicData'
import { getMachineDirectoryTree, getMachineDeviceDetailList } from '@/api/basicCode'

import fileUploader from '@/components/FileUploader'
// import onlyTreeModal from '@/components/TreeModal/onlytree'
import treeModal from './machineSelect.vue'
import BidOpenInfo from '@/components/TreeModal/bidOpenInfo'
export default {
  name: 'AddDeviceLeaseContractInfo',
  components: {
    fileUploader,
    BidOpenInfo,
    treeModal
  },
  props: {
    showModal: {
      type: Boolean,
      default: false
    },
    optType: {
      type: String,
      default: 'add'
    },
    dir: {
      type: Object,
      default() {
        return {}
      }
    },
    data: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      getMachineDirectoryTree,
      getMachineDeviceDetailList,
      showFileModal: false,
      selectRow: null,
      targetList: [],
      deviceLeaseContractInfoLeaseType,
      deviceLeaseContractInfoLeaseNature,
      deviceLeaseContractInfoCountersignType,
      workflowStatus,

      addType: '', // same   under
      visible: false,
      showAdd: false,
      selectedNode: null,
      form: {
        leaseNumber: '',
        contractNumber: '',
        contractName: '',
        contractAmount: '',
        employerName: '',
        employerSign: '',
        signTime: '',
        address: '',
        employeeName: '',
        employeeSign: '',
        leaseType: '',
        leaseNature: '',
        countersignType: '',
        warrantyAmount: '',
        warrantyStartTime: '',
        warrantyEndTime: '',
        payType: '',
        remark: ''
      },
      columns: [
        {
          label: '设备目录编码',
          prop: 'devDirCode',
          slot: 'devDirCode',
          width: '100'
        },
        {
          label: '设备目录名称',
          prop: 'devDirName',
          slot: 'devDirName',
          width: '100'
        },
        // {
        //   label: '设备信息编号',
        //   prop: 'devInfoNumber'
        // },
        // {
        //   label: '设备信息名称',
        //   prop: 'devInfoName'
        // },
        {
          label: '规格',
          prop: 'specification',
          slot: 'specification'
        },
        {
          label: '单位',
          prop: 'unit',
          slot: 'unit'
        },
        {
          label: '租赁数量',
          prop: 'count',
          slot: 'count',
          width: '150'
        },
        {
          label: '租赁开始时间',
          prop: 'startTime',
          slot: 'startTime',
          width: '160'
        },
        {
          label: '租赁结束时间',
          prop: 'endTime',
          slot: 'endTime',
          width: '160'
        },
        {
          label: '租赁单价',
          prop: 'unitPrice',
          slot: 'unitPrice',
          width: '150'
        },
        {
          label: '税率',
          slot: 'taxRate',
          width: '150'
        },
        {
          label: '税金',
          slot: 'taxes',
          width: '150'
        },
        {
          label: '租赁合价',
          prop: 'sumPrice',
          slot: 'sumPrice',
          width: '150'
        },
        {
          label: '计划租期',
          prop: 'planLease',
          slot: 'planLease',
          width: '150'
        },
        {
          label: '备注',
          prop: 'remark',
          slot: 'remark',
          width: '150'
        },
        {
          fixed: 'right',
          label: '操作',
          width: '110',
          prop: 'options',
          slot: 'options'
        }
      ],
      showTargetSetListModal: false,
      showBidOpenInfoModal: false,
      showTargetSupplierSetListModal: false,
      fileList: [
      ],
      rules: {
        contractName: [
          { required: true, message: '请输入合同名称', trigger: 'change' }
        ],
        employerName: [
          { required: true, message: '请输入甲方名称', trigger: 'change' }
        ],
        signTime: [
          { required: true, message: '选择签订时间', trigger: 'change' }
        ],
        employeeName: [
          { required: true, message: '请选择乙方名称', trigger: 'change' }
        ]
      },
      provinceData: [],
      cityData: []
    }
  },
  computed: {
    disableForm() {
      return this.optType === 'detail'
    },
    show: {
      get() {
        return this.showModal
      },
      set(val) {
        this.$emit('update:showModal', val)
      }
    }
  },
  watch: {
    showModal(val) {
      if (val && this.optType !== 'add') {
        this.getDocDetail(this.data.id)
        this.$nextTick(() => {
          Object.keys(this.form).forEach(key => {
            const source = this.data[key]
            if (typeof source === 'boolean') {
              this.form[key] = source ? 1 : 0
            } else {
              this.form[key] = source
            }
          })
        })
      } else if (!val) {
        this.fileList = []
        this.targetList = []
        this.$refs.form.resetFields()
      }
    }
  },
  mounted() {
    this.getRegionData()
  },
  methods: {
    addRow() {
      this.targetList = [
        ...this.targetList,
        {
          devDirCode: '',
          devDirName: '',
          specification: '',
          unit: '',
          count: '',
          startTime: '',
          endTime: '',
          unitPrice: '',
          sumPrice: '',
          planLease: '',
          remark: ''
        }
      ]
    },
    deleteRow() {
      if (this.selectRow) {
        const index = this.targetList.indexOf(this.selectRow)
        this.targetList.splice(index, 1)
      } else {
        this.$message({
          type: 'error',
          message: '请选择对应行'
        })
      }
    },
    deleteTarget(obj) {
      this.targetList.map((item, m) => {
        if (item.devDirCode === obj.devDirCode &&
            item.devDirName === obj.devDirName &&
            item.devInfoName === obj.devInfoName &&
            item.devInfoNumber === obj.devInfoNumber) {
          this.targetList.splice(m, 1)
        }
      })
    },
    getSelectedRows(data) {
      this.targetList = this.targetList.concat(data.map(item => {
        const {
          deviceDirectoryCode: devDirCode,
          deviceDirectoryName: devDirName,
          devName: devInfoName,
          devNumber: devInfoNumber,
          specification,
          assetUnit: unit
        } = item
        return {
          devDirCode, devDirName, devInfoName, devInfoNumber, specification, unit,
          count: '', startTime: '', endTime: '', unitPrice: '', sumPrice: '',
          planLease: '', remark: ''
        }
      }))
    },
    getSelectedRowsBidOpenInfo(obj) {
      // 合同名称 = 招标名称(biName)
      // 合同金额 = 投标金额(boBidPrice)
      // 乙方名称 = 中标单位(boBidUnit)
      this.form.contractName = obj.bidName
      this.form.contractAmount = obj.boBidPrice
      this.form.employeeName = obj.boBidUnit
    },
    provinceChange(e) {
      const selectedData = this.provinceData.filter(val => val.name === e)[0]
      if (selectedData) {
        this.form.city = ''
        const params = {
          parentCode: selectedData.code,
          areaType: 2
        }
        getAreaList(params).then(res => {
          this.cityData = res.data || []
        })
      }
    },
    getDocDetail(id) {
      getDeviceLeaseContractInfoDetail({ deviceLeaseContractInfoId: id }).then(res => {
        const { lstAttachment, lstDeviceLeaseContractDetail } = res.data || {}
        if (lstAttachment && lstAttachment.length > 0) {
          this.fileList = lstAttachment
        }
        if (lstDeviceLeaseContractDetail && lstDeviceLeaseContractDetail.length > 0) {
          this.targetList = lstDeviceLeaseContractDetail
        }
      })
    },
    getRegionData() {
      getAreaList({ areaType: '1' }).then(res => {
        this.provinceData = res.data || []
      })
    },
    saveDoc() {
      if (this.optType === 'detai') {
        this.show = false
        return
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          // if (this.optType === 'add') {
          //   this.form.id = ''
          // } else {
          //   this.form.id = this.data.id
          // }
          const params = {
            deviceLeaseContractInfo: {
              ...this.form,
              ...this.optType === 'edit' ? {
                id: this.data.id
              } : {}
            },
            lstAttachment: this.fileList,
            lstDeviceLeaseContractDetail: this.targetList.map(item => {
              return {
                ...item,
                ...this.optType === 'edit' ? {
                  deviceLeaseContractInfoId: this.data.id
                } : {}
              }
            })
          }
          const fn = this.optType === 'add' ? addDeviceLeaseContractInfo : updateDeviceLeaseContractInfo
          fn(params).then(res => {
            if (res.code === '0001') {
              this.$message({
                type: 'success',
                message: '保存成功!'
              })
              this.show = false
              this.$emit('freshList')
              this.$refs.form.resetFields()
            } else {
              this.$message({
                type: 'error',
                message: res.msg
              })
            }
          })
        }
      })
    },
    inputCount() {
      this.targetList.forEach((item, index) => {
        if (item.count && item.unitPrice) {
          item.sumPrice = Number.parseFloat(item.count) * Number.parseFloat(item.unitPrice)
          item.sumPrice = Number.parseFloat(item.sumPrice).toFixed(2)
        } else {
          item.sumPrice = ''
        }
      })
    },
    inputUnitPrice() {
      this.targetList.forEach((item, index) => {
        if (item.count && item.unitPrice) {
          item.sumPrice = Number.parseFloat(item.count) * Number.parseFloat(item.unitPrice)
          item.sumPrice = Number.parseFloat(item.sumPrice).toFixed(2)
        } else {
          item.sumPrice = ''
        }
      })
    }

  }
}
</script>

<style lang="scss" scoped>
.com-form-title{
  font-size: 14px;
  font-weight: bold;
  line-height: 35px;
  color: #409EFF;
  border-bottom: 1px solid #dedede;
  margin-bottom: 6px;
}
</style>
